package com.zju.DoctorGo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api")
public class FileUploadController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("No file uploaded", HttpStatus.BAD_REQUEST);
        }

        try {
            // 获取文件名并构建目标文件路径
            String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
            Path filePath = Paths.get(uploadDir, fileName);

            // 创建文件夹
            Files.createDirectories(filePath.getParent());

            // 保存文件
            Files.write(filePath, file.getBytes());

            // 返回文件访问的URL
            String fileUrl = "/uploads/" + fileName;
            return new ResponseEntity<>(new UploadResponse(1, fileUrl), HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("File upload failed", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private static class UploadResponse {
        private int code;
        private String url;

        public UploadResponse(int code, String url) {
            this.code = code;
            this.url = url;
        }

        public int getCode() {
            return code;
        }

        public String getUrl() {
            return url;
        }
    }
}
